<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编号" prop="storeNumber" label-width="100px">
              <el-input v-model="queryParams.storeNumber" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="诊所名称" prop="storeName" label-width="100px">
              <el-input v-model="queryParams.storeName" placeholder="请输入诊所名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="级别" prop="status" label-width="100px">
              <el-select v-model="queryParams.level" placeholder="请选择级别" clearable>
                <el-option v-for="dict in busi_store_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="状态" prop="status" label-width="100px">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in busi_store_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:store:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:store:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button v-hasPermi="['business:store:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:store:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
        <el-table-column label="编号" align="center" prop="storeNumber" show-overflow-tooltip />
        <el-table-column label="所属" align="center" prop="agentGdId" min-width="200" show-overflow-tooltip>
          <template #default="scope"> {{ scope.row.agentGdName }} / {{ scope.row.agentSdName }} / {{ scope.row.agentMrName }} </template>
        </el-table-column>
        <!-- <el-table-column label="所属国代" align="center" prop="agentGdName" />
        <el-table-column label="所属省代" align="center" prop="agentSdName" />
        <el-table-column label="所属医代" align="center" prop="agentMrName" /> -->
        <el-table-column label="诊所名称" align="center" prop="storeName" show-overflow-tooltip min-width="100" />
        <el-table-column label="联系电话" align="center" prop="storePhonenumber" show-overflow-tooltip min-width="120" />
        <el-table-column label="总次数" align="center" prop="balanceTotal">
          <template #default="scope">
            {{ parseInt(scope.row.balanceTotal) }}
          </template>
        </el-table-column>
        <el-table-column label="剩余次数" align="center" prop="balanceCurrent">
          <template #default="scope">
            {{ parseInt(scope.row.balanceCurrent) }}
          </template>
        </el-table-column>
        <el-table-column label="已使用次数" align="center" prop="balanceUsed">
          <template #default="scope">
            {{ parseInt(scope.row.balanceUsed) }}
          </template>
        </el-table-column>
        <el-table-column label="今日使用次数" align="center" prop="balanceUsedToday">
          <template #default="scope">
            {{ parseInt(scope.row.balanceUsedToday) }}
          </template>
        </el-table-column>
        <el-table-column label="级别" align="center" prop="level">
          <template #default="scope">
            <dict-tag :options="busi_store_level" :value="scope.row.level" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="busi_store_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="登陆账号" align="center" prop="username" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="120">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button
                v-hasPermi="['business:store:viewDetails']"
                link
                type="primary"
                icon="Search"
                @click="handleViewDetails(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === 0" content="修改" placement="top">
              <el-button v-hasPermi="['business:store:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === 0" content="重置密码" placement="top">
              <el-button v-hasPermi="['business:store:edit']" link type="primary" icon="Key" @click="handleResetPwd(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === 0 && userId !== '1874394082277691393'" content="充值次数" placement="top">
              <el-button v-hasPermi="['business:store:recharge']" link type="success" icon="Money" @click="handleRecharge(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === 0 && userId !== '1874394082277691393'" content="充值金额" placement="top">
              <el-button
                v-hasPermi="['business:store:rechargeAmount']"
                link
                type="success"
                icon="Coin"
                @click="handleRechargeAmount(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === 1" content="重新激活" placement="top">
              <el-button
                v-hasPermi="['business:store:reactivate']"
                link
                type="primary"
                icon="Refresh"
                @click="handleReactivate(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改诊所管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="640px" append-to-body>
      <el-form ref="storeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="form.id" label="所属" prop="agentGdId">
          {{ form.agentGdName }} / {{ form.agentSdName }} / {{ form.agentMrName }}
        </el-form-item>
        <el-form-item v-if="form.id" label="编号" prop="storeNumber">
          <el-input v-model="form.storeNumber" placeholder="请输入诊所编号" disabled />
        </el-form-item>
        <el-form-item v-if="form.id" label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" maxlength="30" disabled />
        </el-form-item>
        <el-form-item label="诊所名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入诊所名称" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" maxlength="30" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="登录密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入登录密码" maxlength="20" />
        </el-form-item>
        <el-form-item label="联系电话" prop="storePhonenumber">
          <el-input v-model="form.storePhonenumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="简介" prop="storeBrief">
          <el-input v-model="form.storeBrief" type="textarea" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="省/市/区" prop="province">
          <el-cascader
            v-model="form.regionInfo"
            :options="regionInfoOptions"
            :props="props"
            popper-class="my-cascader-panel"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <image-upload v-model="form.businessLicense" :limit="1" />
        </el-form-item>
        <el-form-item label="身份证" prop="identityCard">
          <image-upload v-model="form.identityCard" :limit="1" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-radio-group v-model="form.level">
            <el-radio v-for="dict in busi_store_level" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="接收消息" prop="switchMsg">
          <el-radio-group v-model="form.switchMsg">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in busi_store_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogViewDetails.visible" :title="dialogViewDetails.title" width="640px" append-to-body>
      <el-form ref="storeFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item v-if="form.id" label="所属" prop="agentGdId">
          {{ form.agentGdName }} / {{ form.agentSdName }} / {{ form.agentMrName }}
        </el-form-item>
        <el-form-item v-if="form.id" label="编号" prop="storeNumber">
          <el-input v-model="form.storeNumber" placeholder="请输入诊所编号" readonly />
        </el-form-item>
        <el-form-item label="诊所名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入诊所名称" readonly />
        </el-form-item>
        <el-form-item label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" maxlength="30" readonly />
        </el-form-item>
        <el-form-item label="联系电话" prop="storePhonenumber">
          <el-input v-model="form.storePhonenumber" placeholder="请输入联系电话" readonly />
        </el-form-item>
        <el-form-item label="简介" prop="storeBrief">
          <el-input v-model="form.storeBrief" type="textarea" placeholder="请输入简介" readonly />
        </el-form-item>
        <el-form-item label="省/市/区" prop="province">
          <el-cascader v-model="form.regionInfo" :options="regionInfoOptions" :props="props" popper-class="my-cascader-panel" disabled />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" readonly />
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <ImagePreview :width="100" :height="100" :src="form.businessLicenseUrl" :preview-src-list="[form.businessLicenseUrl]" />
        </el-form-item>
        <el-form-item label="身份证" prop="identityCard">
          <ImagePreview :width="100" :height="100" :src="form.identityCardUrl" :preview-src-list="[form.identityCardUrl]" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-radio-group v-model="form.level">
            <el-radio v-for="dict in busi_store_level" :key="dict.value" :value="parseInt(dict.value)" disabled>{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="接收消息" prop="switchMsg">
          <el-radio-group v-model="form.switchMsg">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="parseInt(dict.value)" disabled>{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelViewDetails">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Store" lang="ts">
import { listStore, getStore, delStore, addStore, updateStore, recharge, resetUserPwd, rechargeAmount, reactivate } from '@/api/business/store';
import { StoreVO, StoreQuery, StoreForm } from '@/api/business/store/types';
import CnRegionInfo from '@/assets/data/cn_region_info.json';
import { to } from 'await-to-js';
import useUserStore from '@/store/modules/user';

const { userId } = useUserStore();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { busi_store_level, sys_normal_disable, busi_store_status } = toRefs<any>(
  proxy?.useDict('busi_store_level', 'sys_normal_disable', 'busi_store_status')
);

const storeList = ref<StoreVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const storeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogViewDetails = reactive<DialogOption>({
  visible: false,
  title: ''
});

const props = {
  expandTrigger: 'hover' as const
};
const regionInfoOptions = CnRegionInfo;

const initFormData: StoreForm = {
  id: undefined,
  sysUserId: undefined,
  storeNumber: undefined,
  storeAiKey: undefined,
  storeName: undefined,
  username: '',
  password: '',
  storePhonenumber: undefined,
  storeBrief: undefined,
  country: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  address: undefined,
  businessLicense: undefined,
  identityCard: undefined,
  level: 1,
  balanceTotal: 0,
  balanceCurrent: undefined,
  balanceUsed: undefined,
  switchMsg: 0,
  status: 0,
  remark: undefined
};
const data = reactive<PageData<StoreForm, StoreQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sysUserId: undefined,
    storeNumber: undefined,
    storeAiKey: undefined,
    storeName: undefined,
    storePhonenumber: undefined,
    country: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    address: undefined,
    level: undefined,
    balanceTotal: undefined,
    balanceCurrent: undefined,
    balanceUsed: undefined,
    switchMsg: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '诊所名称不能为空', trigger: 'blur' }],
    username: [
      { required: true, message: '登录账号不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '登录账号长度必须介于 2 和 20 之间', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '登录密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '登录密码长度必须介于 5 和 20 之间', trigger: 'blur' }
    ],
    province: [{ required: true, message: '省/市/区不能为空', trigger: 'blur' }],
    businessLicense: [{ required: true, message: '营业执照不能为空', trigger: 'blur' }],
    identityCard: [{ required: true, message: '身份证不能为空', trigger: 'blur' }],
    storePhonenumber: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    level: [{ required: true, message: '级别不能为空', trigger: 'change' }],
    switchMsg: [{ required: true, message: '是否接收消息不能为空', trigger: 'change' }],
    // status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询诊所管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStore(queryParams.value);
  storeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

const cancelViewDetails = () => {
  reset();
  dialogViewDetails.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  storeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: StoreVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加诊所';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StoreVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getStore(_id);
  Object.assign(form.value, res.data);
  let regionInfo = [];
  if (form.value.province !== undefined) {
    regionInfo.push(form.value.province);
  }
  if (form.value.city !== undefined) {
    regionInfo.push(form.value.city);
  }
  if (form.value.district !== undefined) {
    regionInfo.push(form.value.district);
  }
  form.value.regionInfo = regionInfo;
  dialog.visible = true;
  dialog.title = '修改诊所';
};

const handleViewDetails = async (row?: StoreVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getStore(_id);
  Object.assign(form.value, res.data);
  let regionInfo = [];
  if (form.value.province !== undefined) {
    regionInfo.push(form.value.province);
  }
  if (form.value.city !== undefined) {
    regionInfo.push(form.value.city);
  }
  if (form.value.district !== undefined) {
    regionInfo.push(form.value.district);
  }
  form.value.regionInfo = regionInfo;
  dialogViewDetails.visible = true;
  dialogViewDetails.title = '查看诊所详情';
};

/** 提交按钮 */
const submitForm = () => {
  storeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStore(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addStore(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: StoreVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除诊所编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delStore(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/store/export',
    {
      ...queryParams.value
    },
    `store_${new Date().getTime()}.xlsx`
  );
};

const handleChange = (value: string) => {
  form.value.province = value[0];
  form.value.city = value[1];
  if (value.length === 3) {
    form.value.district = value[2];
  } else {
    form.value.district = '';
  }
};

/** 重置密码按钮操作 */
const handleResetPwd = async (row: StoreVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入诊所"' + row.storeName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
    })
  );
  if (!err) {
    await resetUserPwd(row.sysUserId, res.value);
    proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value);
  }
};

const handleRecharge = async (row: StoreVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入诊所"' + row.storeName + '"的充值次数', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^\d+$/,
      inputErrorMessage: '充值额度必须是一个正整数'
    })
  );
  if (!err) {
    await recharge(row.id, res.value);
    proxy?.$modal.msgSuccess('充值成功' + res.value);
    await getList();
  }
};

const handleRechargeAmount = async (row: StoreVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入诊所"' + row.storeName + '"的充值金额，本操作会涉及提成计算，请谨慎核对充值金额并确认', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^\d+$/,
      inputErrorMessage: '充值金额必须是一个正整数',
      inputValidator: (value) => {
        if (!value.match(/^\d+$/)) {
          return '充值金额必须是一个正整数';
        }
        const amount = parseInt(value, 10);
        if (amount < 6) {
          return '充值金额必须大于等于6';
        }
        return true;
      }
    })
  );
  if (!err) {
    await rechargeAmount(row.id, res.value);
    proxy?.$modal.msgSuccess('充值成功' + res.value);
    await getList();
  }
};

const handleReactivate = async (row?: StoreVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认重新激活诊所名称为"' + row?.storeName + '"的数据项？').finally(() => (loading.value = false));
  await reactivate(_ids);
  proxy?.$modal.msgSuccess('激活成功');
  await getList();
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss">
.my-cascader-panel {
  width: 97% !important; /* 使弹出面板宽度占满屏幕 */
  overflow: auto; /* 添加滚动条以确保内容可滚动 */
}
</style>
